package com.zj.open.wechat.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zj.open.wechat.service.WechatService;

@RestController
@RequestMapping("wx")
public class WechatController {
    @Autowired
    WechatService wechatService;

    @RequestMapping("msg")
    public String message(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce, @RequestParam(value = "echostr", required = false) String echostr,
            @RequestParam(value = "openid", required = false) String openid, @RequestBody(required = false) String body) {

        List<String> params = new ArrayList<String>();
        params.add("ShareCoupon123");
        params.add(timestamp);
        params.add(nonce);
        Collections.sort(params);
        String sha1 = DigestUtils.sha1Hex(StringUtils.collectionToDelimitedString(params, ""));
        if (sha1.equals(signature)) {
            if (echostr != null) {
                return echostr;
            }
            if (openid != null) {
                wechatService.handleMsg(openid, body);
                return "success";
            }
        }
        return null;
    }
}
